package com.devin.controller;

import com.devin.pojo.Role;
import com.devin.pojo.UserInfo;
import com.devin.service.UserService;
import com.github.pagehelper.PageInfo;
import org.apache.ibatis.annotations.Results;
import org.omg.PortableInterceptor.INACTIVE;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
@RequestMapping("/users")
public class UserController {
    @Autowired
    private UserService userService;
    @RequestMapping("/getUsers")
    public ModelAndView index(@RequestParam(value = "page",defaultValue = "1")Integer page
                        ,@RequestParam(value = "size",defaultValue = "5")Integer size){
        List<UserInfo> users = userService.getUsers(page,size);
        PageInfo<UserInfo> userInfoPageInfo = new PageInfo<UserInfo>(users);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("userInfoPageInfo",userInfoPageInfo);
        modelAndView.setViewName("pages/users-pages-list");
        return modelAndView;
    }

    @RequestMapping("/addUser")
    public String addUser(UserInfo user,Integer[] roleIds){
        userService.addUser(user,roleIds);
        return "redirect:/users/getUsers";
    }

    @RequestMapping(value = "/getUserDetails",method = RequestMethod.GET)
    public ModelAndView getUserDetails(Integer userId){
        UserInfo user =userService.getUserById(userId);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("user",user);
        modelAndView.setViewName("pages/user-details");
        return modelAndView;
    }
    /*根据用户id，删除角色，*/
    @RequestMapping("/delRoleByUserId")
    public String delRoleByUserId(Integer userId,Integer roleId){
        userService.delRoleByUserId(userId,roleId);
        return "redirect:/users/getUserDetails?userId="+userId;
    }
    /*查询用户没有的角色*/
    @RequestMapping(value = "/getRoles2Json",method = RequestMethod.POST)
    @ResponseBody
    public List<Role> getRoles2Json(Integer userId){
        return userService.getRoles2Json(userId);
    }
    /*添加用户没有的角色*/
    @RequestMapping("/addRoles")
    public String addRoles(Integer userId,Integer[] roleIds){
        userService.addRoles(userId,roleIds);
        return "redirect:/users/getUserDetails?userId="+userId;
    }
    /*删除单个用户*/
    @RequestMapping("/delUser")
    public String delUser(Integer userId){
        userService.delUser(userId);
        return "redirect:/users/getUsers";
    }
    /*删除选中的用户*/
    @RequestMapping(value = "/delUsersChecked",method = RequestMethod.POST)
    @ResponseBody
    public String delUsersChecked(Integer[] ids){
        userService.delUsersChecked(ids);
        return "success";
    }
}
